import axios from "axios";
axios.defaults.baseURL = "http://192.168.3.16:3002";
// 47.101.63.34
import { showFailToast } from 'vant';
import { useRouter } from "vue-router";
const router = useRouter()
//添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    // console.log(response.data)
    let res = response.data
    if (res.status == 401) {
        
        showFailToast('Token失效 重新登录');
        router.push('/login')
    } else if (res.status == 403) {
        showFailToast('Token未传');
    }else if(res.status == 404){
        showFailToast('接口不存在');
    }else if(res.status == 500){
        showFailToast('服务器错误');
    }else if(res.status == 502){
        showFailToast('服务器错误 网关出错');
    }
    // 直接返回数据层 你如果 一层一层的去打印
    return response
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});

const gethttp = (url: any, method: any, params: object | null | undefined) => {
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method: method,
            params: params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

const posthttp = (url: any, params: any) => {
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method: "post",
            data: params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

const httpGetToken = (url: any, method: any, params: any) => {
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method: method,
            params: params,
            headers: {
                "Authorization": localStorage.getItem("token")
            }
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

const httpPostToken = (url: any, method: any, params: any) => {
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method: method,
            data: params,
            headers: {
                "Authorization": localStorage.getItem("token")
            }
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

export { gethttp, posthttp, httpGetToken, httpPostToken }